<template>
  <div>
    <!-- 外部 -->
    <el-dialog
      class="dialog"
      title="选择商品"
      :visible.sync="visibleSelect"
      :before-close="seckillGoodsClose"
      width="80%"
      top="6vh"
    >
      <!-- 规格添加 -->
      <el-dialog
        class="dialog"
        width="80%"
        title="选择规格"
        :visible.sync="visibleSpec"
        append-to-body
        top="6vh"
      >
        <div slot="footer" class="dialog-footer-spec">
          <el-button @click="visibleSpec = false">取 消</el-button>
          <el-button type="primary" @click="specSubmit">确认</el-button>
        </div>
        <div v-if="listSpec.length">
          <p>商品名称: {{ specName }}</p>
          <el-table :data="listSpec" style="width: 100%" border>
            <el-table-column :label="listSpec[0].attr_name[0].name" width="200">
              <template slot-scope="scope">
                <div v-for="(item, index) of listSpec" :key="index" v-if="index === scope.$index">{{ item.option_value[0] }}</div>
              </template>
            </el-table-column>

            <el-table-column label="是否参加" width>
              <template slot-scope="scope">
                <div>
                  <el-switch
                    v-model="formlist[scope.$index].is_join"
                    @change="statusChange(scope.row)"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="spec_kucun" label="现库存" width="300" />
            <el-table-column prop="spec_price" label="现价" width="300" />
            <el-table-column label="秒杀库存" width="150">
              <template slot-scope="scope">
                <div>
                  <el-input-number
                    v-model="formlist[scope.$index].spec_seckill_kucun"
                    size="mini"
                    controls-position="right"
                    :min="0"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="秒杀价" width="150">
              <template slot-scope="scope">
                <div>
                  <el-input-number
                    v-model="formlist[scope.$index].spec_seckill_price"
                    size="mini"
                    controls-position="right"
                    :min="0"
                  />
                </div>
              </template>
            </el-table-column>
          </el-table>
          <el-form>
            <el-form-item label="每人限购（0表示不限购）" style="margin-top:10px">
              <template>
                <div>
                  <el-input v-model="limit_num" style="width:150px;">
                    <template slot="append">件</template>
                  </el-input>
                </div>
              </template>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
      <!-- 批量添加 -->
      <el-dialog
        class="dialog"
        width="80%"
        top="6vh"
        title="批量添加"
        :visible.sync="visibleBatch"
        append-to-body
      >
        <div slot="footer" class="dialog-footer-batch">
          <el-button @click="visibleBatch = false">取 消</el-button>
          <el-button type="primary" @click="multipleSubmit">确认</el-button>
        </div>
        <el-table :data="multipleSelection" style="width: 100%" border>
          <el-table-column>
            <template slot-scope="scope">
              <div>
                <el-avatar :size="60" :src="scope.row.img_show" shape="square" />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="名称" width="200" />
          <el-table-column prop="inventory" label="现库存" width="200" />
          <el-table-column prop="price" label="现价" width="200" />
          <el-table-column prop="seckill_price" label="秒杀价" width>
            <template slot-scope="scope">
              <div>
                <el-input v-model="scope.row.seckill_price" size="medium" placeholder="请输入内容" />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="seckill_kucun" label="每个规格的秒杀库存" width>
            <template slot-scope="scope">
              <div>
                <el-input v-model="scope.row.seckill_kucun" size="medium" placeholder="请输入内容" />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="limit_num" label="每个限购（0表示不限购）" width>
            <template slot-scope="scope">
              <div>
                <el-input v-model="scope.row.limit_num" size="medium" placeholder="请输入内容" />
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
      <div slot="title" class="dialog-footer">
        <h3>{{ editName }}</h3>
        <div v-if="!isEdit">
          <el-button @click="visibleSelect = false">取 消</el-button>
          <el-button type="primary" @click="multipleAdd">批量添加</el-button>
        </div>
      </div>
      <div class="bottom-content">
        <div class="d-flex">
          <Search v-if="!isEdit" placeholder="请输入名称" class="mr-15" @search="handleSearch" />
          <el-form
            :inline="true"
            class="demo-form-inline mr-15"
            style="white-space: nowrap; margin: 0"
          >
            <el-form-item v-if="!isEdit" label="分类筛选：" style="margin: 0">
              <!-- <el-select v-model="value1" clearable placeholder="全部" @change="selectChange">
                <el-option
                  v-for="item of classicList"
                  :key="item.id"
                  :label="item.kind_name"
                  :value="item.id"
                />
              </el-select>-->
              <el-cascader
                v-model="kind"
                size="small"
                :options="kindList"
                :props="casProps"
                expand-trigger="hover"
                clearable
                @change="handleCascader"
              />
              <!-- <el-cascader v-model="value" placeholder="全部" :options="classicList" clearable @change="handleChange" /> -->
            </el-form-item>
          </el-form>
        </div>
        <div class="mt-35">
          <el-table
            ref="multipleTable"
            :data="listMng"
            tooltip-effect="dark"
            border
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width />
            <el-table-column label="图片" width="100">
              <template slot-scope="scope">
                <div>
                  <el-avatar :size="60" :src="scope.row.img_show" shape="square" />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="名称" width>
              <template slot-scope="scope">{{ scope.row.name }}</template>
            </el-table-column>
            <el-table-column prop="price" label="现价" width />
            <el-table-column prop="sold_out" label="现有销量" />
            <el-table-column prop="inventory" label="实际库存" />
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" @click="addSpec(scope.row)">添加规格</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <Pagination
          v-if="!isEdit"
          class="pagination"
          :total="total"
          :cur-page="currentPgae"
          @nextPage="handleNextPage"
        />
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Search from '@/common/input'
import Pagination from '@/common/pagination'
import {
  getSecKillGoodsMngList,
  getSpecGoodsMng,
  addSeckillMng,
  multipleAddMng
} from '@/api/seckill'
import { getPropClassList } from '@/api/good-mng'
const ERR_OK = 200
export default {
  components: {
    Search,
    Pagination
  },
  props: {
    seckillId: {
      type: [Number, String],
      default: ''
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    seckillItem: {
      type: Array,
      default: () => []
    },
    editName: {
      type: String,
      default: '编辑商品'
    }
  },
  data() {
    return {
      calcuInventory: '',
      circleUrl:
        'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      visibleSelect: false,
      visibleSpec: false,
      visibleBatch: false,
      query: '',
      value1: '',
      multipleSelection: [],
      currentPgae: 1,
      listMng: [],
      listSpec: [],
      formlist: [],
      limit_num: 0,
      kindList: [],
      specName: '',
      total: 0,
      casProps: {
        expandTrigger: 'hover',
        // checkStrictly: true,
        value: 'id',
        label: 'kind_name',
        children: 'lower'
      },
      kind: [],
      second_cate_id: '',
      seckillGoodsList: []
    }
  },
  watch: {
    seckillItem: {
      deep: true,
      immediate: true,
      handler(newVal) {
        console.log(newVal, '测试')
        this.listMng = newVal
      }
    },
    isEdit(newVal) {
      if (!newVal) {
        this.currentPgae = 1
        this._getSecKillGoodsMngList({ page: this.currentPgae })
      }
    }
  },
  created() {
    getPropClassList().then(res => {
      if (res.code === 200) {
        this.kindList = res.data
      }
    })
    this._getSecKillGoodsMngList({ page: this.currentPgae })
  },
  methods: {
    seckillGoodsClose() {
      this.visibleSelect = false
    },
    handleCascader(val) {
      this.currentPgae = 1
      const second_cate_id = val[1]
      this.second_cate_id = second_cate_id
      this._getSecKillGoodsMngList({
        page: this.currentPgae,
        keyword: this.query,
        second_cate_id
      })
    },
    multipleAdd() {
      if (this.multipleSelection.length) {
        this.visibleBatch = true
      } else {
        this.$message({
          message: '请选择商品',
          type: 'warning',
          showClose: true
        })
      }
    },
    multipleSubmit() {
      this.visibleBatch = false
      this.multipleSelection.forEach((item, index) => {
        item.commodity_id = item.id
      })
      this._multipleAddMng({
        id: this.seckillId,
        commodity_info: JSON.stringify(this.multipleSelection)
      }).then(() => {
        this.$emit('selectSeckillGoods')
      })
    },
    specSubmit() {
      const _formlist = JSON.parse(JSON.stringify(this.formlist))
      _formlist.forEach((item, index) => {
        item.is_join = item.is_join ? 1 : 0
      })
      let is_add = 0
      if (!this.isEdit) {
        is_add = 0
      } else {
        is_add = 1
      }
      this._addSeckillMng(
        JSON.stringify(_formlist),
        this.limit_num,
        this.seckillId,
        this.goodsId,
        is_add
      ).then(() => {
        this.visibleSpec = false
        this.$emit('selectSeckillGoods')
      })
    },
    handleNextPage(page) {
      this.currentPgae = page
      this._getSecKillGoodsMngList({
        page: this.currentPgae,
        keyword: this.query,
        second_cate_id: this.second_cate_id
      })
    },
    show() {
      this.visibleSelect = true
    },
    handleSearch(query) {
      this.query = query
      this.currentPgae = 1
      this._getSecKillGoodsMngList({
        page: this.currentPgae,
        keyword: this.query
      })
    },
    handleSelectionChange(val) {
      val.forEach((item, index) => {
        item.seckill_price = 0
        item.seckill_kucun = 0
        item.limit_num = 0
      })
      this.multipleSelection = val
    },
    addSpec(row) {
      this.visibleSpec = true
      if (!this.isEdit) {
        this._getSpecGoodsMng(row.id)
      } else {
        this._getSpecGoodsMng(row.id, this.seckillId)
      }
      this.goodsId = row.id
    },
    statusChange(row) {},
    _getSecKillGoodsMngList({ page, keyword, second_cate_id }) {
      getSecKillGoodsMngList({ page, keyword, second_cate_id })
        .then(res => {
          if (res.code === ERR_OK) {
            this.listMng = res.data.list

            this.total = res.data.total
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    _getSpecGoodsMng(id, seckillId) {
      getSpecGoodsMng(id, seckillId)
        .then(res => {
          if (res.code === ERR_OK) {
            console.log(res)
            this.listSpec = res.data.list
            this.formlist = []
            this.listSpec.forEach((item, index) => {
              this.formlist.push({
                sku_id: item.sku_id,
                commodity_id: item.commodity_id,
                spec_ids: item.spec_ids,
                is_join: true,
                spec_kucun: item.spec_kucun,
                spec_price: item.spec_price,
                spec_seckill_kucun: item.spec_seckill_kucun,
                spec_seckill_price: item.spec_seckill_price
              })
            })
            this.specName = res.data.name
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    _addSeckillMng(params, limit_num, seckill_id, id, is_add) {
      return addSeckillMng(params, limit_num, seckill_id, id, is_add)
        .then(res => {
          if (res.code === ERR_OK) {
            this.$message({
              message: res.message,
              showClose: true,
              type: 'success'
            })
            return Promise.resolve()
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    _multipleAddMng({ id, commodity_info }) {
      return multipleAddMng({ id, commodity_info })
        .then(res => {
          if (res.code === ERR_OK) {
            this.$message({
              message: res.message,
              showClose: true,
              type: 'success'
            })
            return Promise.resolve()
          }
        })
        .catch(err => {
          console.log(err)
        })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "@/styles/el-table.scss";
@import "@/styles/el-pagination.scss";
@import "@/styles/el-button.scss";
.el-button:hover {
  color: #fff;
}
.el-button {
  color: #ffff;
}
.el-dialog__wrapper /deep/.el-dialog__headerbtn {
  position: absolute;
  top: -30px;
  right: 0;
  border-radius: 50%;
  background: #fff;
  width: 25px;
  height: 25px;
  font-size: 22px;
}
.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.d-flex {
  display: flex;
  align-items: center;
}
.mt-35 {
  margin-top: 35px;
}
.mr-15 {
  margin-right: 15px;
}
.pagination {
  justify-content: center;
}
.dialog {
  min-width: 1200px;
}
</style>
